/**
 * @author yzhou2
 */
var QS_DateFormat={
    formatMDYDate:function(dt){//dt Date
        return (dt==null)?" " : DTFormat.Mo[dt.getMonth()]+" "+(dt.getDate()<10?"0"+dt.getDate():dt.getDate())+", "+dt.getFullYear();
    },
    transMDYDate:function(d){//yyyy-mm-dd
       if(d==null){
            return '';
       }else{
           var arr=d.split('-'),
              y=arr[0],
              m=parseInt(arr[1],10)-1,
              day=arr[2];
           return DTFormat.Mo[m]+" "+day+","+y;
       }
       
    },
    formatDate:function(date){//Date
        if (date == null) {
            return null;
        }
        return date.getFullYear()+"-"+QS_DateFormat.formateNum(date.getMonth()+1)+"-"+QS_DateFormat.formateNum(date.getDate());
    },
    formatDate1:function(date){//Date
        if (date == null) {
            return null;
        }
        return date.getFullYear()+"-"+QS_DateFormat.formateNum(date.getMonth()+1)+"-"+QS_DateFormat.formateNum(date.getDate())+"T"+QS_DateFormat.formateNum(date.getHours()) + ":" + QS_DateFormat.formateNum(date.getMinutes())+":"+QS_DateFormat.formateNum(date.getSeconds());
    },
    compareWithToday:function(d){//yyyy-mm-dd
        var today=QS_DateFormat.formatDate(new Date());
        var arr=today.split('-');
        var tStr=arr.join('');
        var tInt=parseInt(tStr,10);
        var arr1=d.split('-');
        var dStr=arr1.join('');
        var dInt=parseInt(dStr,10);
        return dInt-tInt;
    },
    formateNum:function(d){
        return d < 10 ? "0" + d : d.toString(); 
    },
    convertDate:function(d){//convert yyyy-mm-dd to date format
        var arr=d.split('-');
        return new Date(parseInt(arr[0],10),parseInt(arr[1],10)-1,parseInt(arr[2],10));
    },
	convertToDate:function(d){//convert yyyy/mm/dd'T'HH:mm:ss to date format
        d=d.split('T');
		var dt=d[0].split('-'),tm=d[1].split(':');
		return new Date(parseInt(dt[0],10),parseInt(dt[1],10)-1,parseInt(dt[2],10),parseInt(tm[0],10),parseInt(tm[1],10),parseInt(tm[2],10));
    },
    setTime:function(date,type){
        var h=0,m=0,s=0;
        if(type=='now'){
            var now=new Date();
            h=now.getHours();
            m=now.getMinutes();
            s=now.getSeconds();
        }else if(type=='max'){
            h=23;
            m=59;
            s=59;   
        }
        date.setHours(h);
        date.setMinutes(m);
        date.setSeconds(s);
        return date;
    },
    toUSDate:function(d){
         if (d == ""&&t=="") {
            return "";
        }
        var date=d.split("T")[0];
        var time=d.split("T")[1].substring(0,5);
        var ds = date.split("-");
        
        var month = parseInt(ds[1], 10),
            day = parseInt(ds[2], 10);  
        return month+"/"+day+" "+time;
    },
    toDateTime:function(d){
        if (d == ""&&t=="") {
            return "";
        }
        var date=d.split("T")[0];
        var time=d.split("T")[1].substring(0,5);
        var ds = date.split("-");
        return parseInt(ds[1], 10)+"/"+parseInt(ds[2], 10)+"/"+parseInt(ds[0], 10)+", "+time;
    },
    toESTTime:function(d){
        if (d == ""&&t=="") {
            return "";
        }
        var date=d.split("T")[0];
        var time=d.split("T")[1];
        var ds = date.split("-");
        var ts = time.split(":");
        
        var year = parseInt(ds[0], 10),
            month = parseInt(ds[1], 10),
            day = parseInt(ds[2], 10),
            hour = parseInt(ts[0],10),
            min = parseInt(ts[1],10),
            sec = parseInt(ts[2],10);
         return this.toDateTime(this.formatDate1(new Date(year,month-1,day,hour+1,min,sec)));
    },
    toESTDate:function(d){//yyyy-MM-dd'T'HH:mm:ss
        if (d == ""&&t=="") {
            return "";
        }
        var date=d.split("T")[0];
        var time=d.split("T")[1];
        var ds = date.split("-");
        var ts = time.split(":");
        
        var year = parseInt(ds[0], 10),
            month = parseInt(ds[1], 10),
            day = parseInt(ds[2], 10),
            hour = parseInt(ts[0],10),
            min = parseInt(ts[1],10),
            sec = parseInt(ts[2],10);
        return this.toUSDate(this.formatDate1(new Date(year,month-1,day,hour+1,min,sec)));
    }
};
var QS_NewsDataManager=function(){
    this.DEFAULT_TYPE='default';
    this.BRF_INPLAY_TYPE='BRIEFING_INPLAY';
    this.BRF_TRADER_TYPE='BRIEFING_TRADER';
    this.sourcePermission=typeof QSPC!='undefined'?QSPC.getConfig(2):{};
    this.protocol = typeof(QS_PROTOCOL)=="undefined"?"http://":QS_PROTOCOL;
    this.dataURL={
        newsOverview:"getNewsOverview.jsp",
        newsTitle:"getNewsTitle.jsp",
        newsContent:"getNewsContent.jsp",
        newsSource:"getNewsSource.jsp",
        template:"template.jsp",
        getTickerInfoURL :this.protocol+"qt.morningstar.com/switchservice/getids.ashx?d=1&" // get ticker information url.
    };
    this.getDataCallback=null;
    this.MstarSourceCodeList=[2001,2002,2003,2004,2005,2006,2007,2009,2010,
                              2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,
                              2021,2022,2023,2024,2025,2026,2027,2028,2029,2030,
                              2031,2032,2033,2034,2035,2036,2037,2038,2039,2040];
    this.PRSourceCodeList=[4001,4003,4005,4007,4009,4010,4011,4014,4015,4021,4029,4030,4031,4032,4033,4034,4035,4037];
    this.bCoreVersion=[3081,3082,3083,3084,3085,3080,3089,3093,3143];
    this.bInplayVersion=[3081,3082,3083,3084,3085,3087,3090,3094,3096,3099,
                         3100,3101,3102,3103,3104,3105,3106,3107,3108,3109,
                         3110,3111,3112,3113,3114,3115,3116,3117,3118,3144];
    this.bTraderVersion=[3081,3082,3083,3084,3085,3088,3091,3095,3097,3119,
                         3120,3121,3122,3123,3124,3125,3126,3127,3128,3129,
                         3130,3131,3132,3133,3134,3135,3136,3137,3138,3139,
                         3140,3141,3142,3145]
    this.MstarFundSourceCodeList=[2012,2039,2038,2004,2034,2036,2003,2017,2035,2009,2032,2022];
    this.BriefingCoreSourceCodeList = this.sourcePermission["3006"] ? this.bTraderVersion : this.sourcePermission["3044"] ? this.bInplayVersion : this.bCoreVersion;
    this.registeredNews = [];
    this.openedList={
        'default':[-1,-2,-3,-4,-5,-6,-7,-8,-9,-10],
        'BRIEFING_INPLAY':[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
        'BRIEFING_TRADER':[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
    };
    this.currentViewID={
        'default':-1,
        'BRIEFING_INPLAY':0,
        'BRIEFING_TRADER':0
    };
    this.defaultViewList=[{txt:'All',val:'msview',vid:-1},{txt:'Morningstar',val:'msview', vid:-2},{txt:'AP',val:'msview', vid:-3},
    {txt:'Briefing',val:'msview', vid:-4},{txt:'PR',val:'msview', vid:-5},{txt:'Funds',val:'msview', vid:-6},
    {txt:'Stock Analysis',val:'msview', vid:-7},{txt:'Need to Know',val:'msview', vid:-8},{txt:'FOREX',val:'msview', vid:-9},
    {txt:'Alerts',val:'msview', vid:-10},{txt:'Markets & Economy',val:'msview', vid:-11},{txt:'Stocks News',val:'msview', vid:-12}];
    this.defaultViewSource={
        '-1':{      
            'ntSource':this.MstarSourceCodeList.concat(this.PRSourceCodeList).concat(this.BriefingCoreSourceCodeList).concat([4008])  
        },
        '-2':{
            'ntSource':this.MstarSourceCodeList
        },
        '-3':{
            'ntSource':['4002']
        },
        '-4':{
            'ntSource':this.BriefingCoreSourceCodeList
        },
        '-5':{
            'ntSource':this.PRSourceCodeList
        },
        '-6':{
            'ntSource':this.MstarFundSourceCodeList
        },
        '-7':{
            'ntSource':[2001,2002]
        },
        '-8':{
            'ntSource':[4029]
        },
        '-9':{
            'ntSource':[4008]
        },
        '-10':{
            'dcSource':['M*A']
        },
        '-11':{
            'ntSource': ['3081','3082','3083','3084','3085','3080','3089','3093','3143','4008']
        },
		'-12':{
			'ntSource': ["1001","1002","4009", "4005", "4007", "4030", "4037", "4010", "4014", "4031", "4021", "4029", "4034", "4033", "4001", "4035", "4003", "4011", "4015", "4032","4023", "4024", "4026", "4038", "4042", "4039", "4025", "4004", "4036", "4006", "4022", "4027", "4040", "4041", "4028",'4044','4043']
		}
    };
    this.briefingViewList=[{
        val:'Allnews',
        txt:'All',
        vid:0
    },{
        val: 'BrokerResearch',
        txt: 'Research',
        vid: 1
    },{
        val: 'Commentary',
        txt: 'Commentary',
        vid: 2
    },{
        val: 'Earnings',
        txt: 'Earnings',
        vid: 3
    },{
        val: 'Econ',
        txt: 'Economic',
        vid: 4
    },{
        val: 'News',
        txt: 'News',
        vid: 5
    },{
        val: 'Options',
        txt: 'Options',
        vid: 6
    },{
        val: 'Profiles',
        txt: 'Profiles',
        vid: 7
    },{
        val: 'Rumors',
        txt: 'Rumors',
        vid: 8
    },{
        val: 'Summaries',
        txt: 'Summaries',
        vid: 9
    },{
        val: 'TechnicalAnalysis',
        txt: 'Technical',
        vid: 10
    },{
        val: 'TopEvents',
        txt: 'Top Events',
        vid: 11
    },{
        val: 'GeneralTradingCalls',
        txt: 'General',
        vid: 12
    },{
        val: 'IntraDayTrades',
        txt: 'Intra-Day',
        vid: 13
    },{
        val: 'ScalpTrades',
        txt: 'Scalp Trades',
        vid: 14
    },{
        val: 'SwingTrades',
        txt: 'Swing Trades',
        vid: 15
    }];
    this.briefingViewSource={};
//  this.openedViewList=null;
    this.defaultStatus=false;
    this.briefingStatus=true;
	this.defaultViewListMap={};
    this._runViewChecker();
};
QS_NewsDataManager.prototype={
    setSourcePermission:function(cfg){
        this.sourcePermission=cfg;
        this._runViewChecker();
    },
    register:function(id){
        var flag=false;
        for(var i=0;i<this.registeredNews.length;i++){
            if(this.registeredNews[i]==id){
                flag=true;
                break;
            }
        }
        if(!flag){//not exist
            this.registeredNews.push(id);
        }
    },
    unregister:function(id){
        var flag=0;
        for(var i=0;i<this.registeredNews.length;i++){
            if(this.registeredNews[i]==id){
                flag=i;
                break;
            }
        }
        if(flag>=0){//exist
            this.registeredNews.splice(flag,1);
        }
    },
    getViewList:function(type,callback){
        var self=this;
        if (type == this.DEFAULT_TYPE) {
            if(this.defaultStatus){
                callback(this.defaultViewList);
            }else{
                if(QS_UserID != null) {
                    var data = { type: '21', action:'gettmplist', tmpid:QS_UserTID };
                    this._post(this.dataURL.template,data, function(d){
                        if (d != "") {
                            d = eval("(" + d + ")");
                            if (d.temp) {
                                var o = d.temp;
                                if(self.defaultViewList==null){
                                    self.defaultViewList=[];
                                }
                                for (var i = 0, l = o.length; i < l; i++) {
                                    self.defaultViewList.push({
                                        txt: o[i].title,
                                        vid: o[i].id,
                                        val: 'myview'
                                    });
                                }
                            }
                        }
                        self.defaultStatus=true;
                        callback(self.defaultViewList);
                    });
                }
            }
        }else{
            if(this.briefingStatus){
                callback(this.briefingViewList);
            }else{
                self.defaultStatus=true;
            }
        }
    },
	convertDefaultViewListToMap:function(){
		var map={};
		for(var i=0,l=this.defaultViewList.length;i<l;i++){
			map[this.defaultViewList[i].vid]=this.defaultViewList[i];
		}
		return map;
	},
    _runViewChecker:function(){
        this._runDefaultViewChecker();
        this._runBriefingViewChecker();
    },
    _runDefaultViewChecker:function(){
        var ids=[];
        if(!this.sourcePermission.ntSourceList||(this.sourcePermission.ntSourceList.hasOwnProperty("4002")&&!this.sourcePermission.ntSourceList["4002"])){
            ids.push('-3');
        }
        if(!this.sourcePermission.ntSourceList||(this.sourcePermission.ntSourceList.hasOwnProperty("2001")&&!this.sourcePermission.ntSourceList["2001"])){
            ids.push('-7');
        }
        if (ids.length > 0) {
            this._spliceDefaultView(ids);
        }
    },
    _runBriefingViewChecker:function(){
        if(this.sourcePermission.b_sourceList!=null){
            var val;
            for(var i=0;i<this.briefingViewList.length;i++){
                val=this.briefingViewList[i].val;
                if(this.sourcePermission.b_sourceList.hasOwnProperty(val)&&!this.sourcePermission.b_sourceList[val]){
                    this.briefingViewList.splice(i,1);
                }
            }
        }
    },
    _spliceDefaultView:function(ids){
        for(var j=0,len=ids.length;j<len;j++){
            var idx=-1;
            for(var i=0;i<this.defaultViewList.length;i++){
                if(this.defaultViewList[i].vid==ids[j]){
                    idx=i;
                    break;
                }
            }
            if (idx != -1) {
                this.defaultViewList.splice(idx, 1);
            }
            var index=-1;
            for(var i=0;i<this.openedList['default'].length;i++){
                if(this.openedList['default'][i]==ids[j]){
                    index=i;
                    break;
                }
            } 
            if (index != -1) {
                this.openedList['default'].splice(index, 1);
            }
        }
    },
    saveViewSource:function(id,profile,callback){
        var self=this;
        var pro = $.toJSON(profile);
        if (QS_UserID != null) {
            var data = {
                tplId: id,
                profile: pro,
                action: 'savetmp',
                tmpid: QS_UserTID
            };
            this._post(this.dataURL.template, data, function(o){
                if (o == 'true') {
                    self.defaultViewSource[id] = profile;
                    if(typeof callback=='function'){
                        callback(true);
                    }
                }else{
                    if(typeof callback=='function'){
                        callback(false);
                    }
                }
            });
        }
    },
    createViewSource:function(profile,callback){
        var self=this;
        var pro = $.toJSON(profile);
        if (QS_UserID != null) {
            var data = {
                type: '21',
                profile: pro,
                title: profile.title,
                action: 'addtmp', 
                tmpid: QS_UserTID
            };
            this._post(this.dataURL.template, data, function(o){
                if (o != null && o != ''&&parseInt(o,10)>0) {
                    self.defaultViewList.push({
                        vid:o,
                        txt:profile.title,
                        val:'myview'
                    });
                    self.defaultViewSource[o] = profile;
                    if(typeof callback=='function'){
                        callback(parseInt(o,10));
                    }
                }else{
                    if(typeof callback=='function'){
                        callback(-1);
                    }
                }
            });
        }
    },
    deleteViewSource:function(id,callback){
        var self=this;
        if (QS_UserID != null) {
            var data = { tplId: id, action:'deltmp', tmpid: QS_UserTID};
            this._post(this.dataURL.template, data, function(o){
                if(o=='true'){
                    for(var i=0,l=self.defaultViewList.length;i<l;i++){
                        if(self.defaultViewList[i].vid==id){
                            self.defaultViewList.splice(i,1);
                            break;
                        }
                    }
                    delete self.defaultViewSource[id];
                    if(typeof callback=='function'){
                        callback(true);
                    }
                }else{
                    if(typeof callback=='function'){
                        callback(false);
                    }
                }
            });
        }
    },
    getViewSourceById:function(id,type,callback){
        var self=this;
        if (type == this.DEFAULT_TYPE) {
            if (this.defaultViewSource && this.defaultViewSource[id]) {
				if(callback){
					callback(this.defaultViewSource[id]);
				}
				return this.defaultViewSource[id];
            }else {
                if (QS_UserID != null) {
                    var data = {
                        tplId: id.toString().replace(/[^0-9]/g, ''),
                        action: 'gettmp',
                        tmpid: QS_UserTID
                    };
                    this._post(this.dataURL.template, data, function(o){
                        if (o != '') {
                            o = eval("(" + o + ")");
                            self.defaultViewSource[id] = o;
                        }
                        if (callback) {
                            callback(self.defaultViewSource[id]);
                        }
						return self.defaultViewSource[id];
                    });
                }
            }
        }else{
            if(this.briefingViewList && this.briefingViewList[id]) {
				if (callback){
					callback(this.briefingViewList[id]);
				}
				return this.briefingViewList[id];
            }else{
				if (callback){
					callback(this.briefingViewList[id]);
				}
				return this.briefingViewList[id];
            }
        }
    },
    getDefaultViewListByGroup:function(group){
        var ret=[];
        if(this.defaultViewList!=null){
            for(var i=0,l=this.defaultViewList.length;i<l;i++){
                if(this.defaultViewList[i].val==group){
                    ret.push(this.defaultViewList[i]);
                }
            }
        }
        return ret;
    },
    getNewsOverview:function(data,callback){
        this._post(this.dataURL.newsOverview,data,function(o){
            if(typeof callback == "function"&&typeof data!='undefined'){
                callback(o);
            }
        });
    },
    getNewsTitleList:function(data,callback){
        this._post(this.dataURL.newsTitle,data,function(o){
            if(typeof callback == "function"&&typeof data!='undefined'){
                callback(o);
            }
        });
    },
    getNewsContent:function(data,callback){
        this._post(this.dataURL.newsContent,data,function(o){
            if(typeof callback == "function"&&typeof data!='undefined'){
                callback(o);
            }
        });
    },
    getNewsSourceList:function(data,callback){
        this._post(this.dataURL.newsSource,data,function(o){
            if (typeof callback == "function" && typeof data != 'undefined') {
                callback(o);
            }
        });
    },
    _get:function(url,callback){
        $.get(url,function(data){
            if(typeof callback == "function"&&typeof data!='undefined'){
                callback(data);
            }
         });
    },
    _post:function(url,data,callback){
        $.post(url,data,function(o){
            if(typeof callback == "function"&&typeof data!='undefined'){
                callback(o);
            }
        });
    },
    inArray:function(elem,array){
        var ret=-1;
        for(var i=0,l=array.length;i<l;i++){
            if(elem==array[i]){
                ret=i;
                break;
            }
        }
        return ret;
    },
	getTickerInfo:function(symbol,getDataCallback){
		$.getJSON(this.dataURL.getTickerInfoURL + "symbol=" + symbol + "&cb=?",function(data){
             var rs;
             if (data != null && data.Records != null && data.Records.length != 0) {
                 rs = data.Records;
             }
             getDataCallback(rs);
        });
	},
    checkTickerInfo:function(symbol,getDataCallback){
	    if (symbol == "") {
            return false;
        }    
        if(typeof getDataCallback=='function'){
            this.getDataCallback=getDataCallback;
        }
        var url = this.dataURL.getTickerInfoURL + "symbol=" + symbol + "&cb=GB_NewsDataManager.onTickerInfoArrived";
        $.getScript(url);
    },
    onTickerInfoArrived:function(data){
        var tickers=[];
        if (data == null || data.Records == null || data.Records.length == 0) {
            
        }else {
            var rs = data.Records,gkey,tickers = [];
            tenforInfo = rs.TenforeInfo;
            if (tenforInfo && tenforInfo.length > 1) {
                gkey = tenforInfo[1]+":"+tenforInfo[0];
                if((rs.Region.toUpperCase()== "USA")||(rs.Type=="XI"&&rs.Domicile=="USA")){// USA sercurity
                    gkey = "126:"+tenforInfo[0];
                }
                if (!gData[gkey] || !gData[gkey]["checked"]) {
                    if(!gData[gkey])gData[gkey] = {};
                    
                }
            }
            if(typeof gData=='undefined'){
                gData={};
            }
            for (var i = 0, l = rs.length; i < l; i++) {
                secId=rs[i].SID;
                if (secId!=null&&secId!='') { // use performanceId as ticker key.
                    tickers.push(secId);
                    gData[secId]={
                        Name:rs.Name,
                        ticker:rs.ticker
                    }
                }
            }          
        }
        this.getDataCallback(tickers,rs);
    }
};
var GB_NewsDataManager=new QS_NewsDataManager();